package com.guigu.controller;

import com.guigu.pojo.Supplier;
import com.guigu.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.pojo.Consumer;
import com.guigu.pojo.Merchant;
import com.guigu.pojo.Supplier;
import com.guigu.pojo.UserAddress;
import com.guigu.service.ConsumerService;
import com.guigu.service.SupplierService;
import com.guigu.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;

/**
 * <p>
 * 供货商信息表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ConsumerService consumerService;

    @GetMapping("/list")
    public Map<String, Object> getSupplierList(@RequestParam(required = false) String companyName, @RequestParam(required = false) String type, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int pageSize) {
        System.out.println("接收到的参数: companyName=" + companyName + ", type=" + type + ", page=" + page + ", pageSize=" + pageSize);
        List<Supplier> supplierList = supplierService.getSupplierWithConsumerNicknameList(companyName, type, page, pageSize);
        int total = supplierService.getSupplierCount(companyName, type);
        Map<String, Object> result = new HashMap<>();
        result.put("list", supplierList);
        result.put("total", total);
        return result;
    }

    @DeleteMapping("/{supplierId}")
    public Map<String, Object> deleteSupplierById(@PathVariable Integer supplierId) {
        int count = supplierService.deleteSupplierById(supplierId);
        Map<String, Object> result = new HashMap<>();
        if (count > 0) {
            result.put("success", true);
            result.put("message", "删除成功");
        } else {
            result.put("success", false);
            result.put("message", "删除失败");
        }
        return result;
    }

    @PutMapping
    public Map<String, Object> updateSupplier(@RequestBody Supplier supplier) {
        int count = supplierService.updateSupplier(supplier);
        Map<String, Object> result = new HashMap<>();
        if (count > 0) {
            result.put("success", true);
            result.put("message", "修改成功");
        } else {
            result.put("success", false);
            result.put("message", "修改失败");
        }
        return result;
    }



    @GetMapping("/getSupplierByConsumerId")
    @ResponseBody
    public Supplier getSupplierByConsumerId(Integer consumerId) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id", consumerId);
        Supplier supplier = supplierService.getOne(queryWrapper);
        return supplier;
    }

    @PostMapping("/saveSupplier")
    @ResponseBody
    @Transactional
    public Supplier updateUser(@RequestParam("files") MultipartFile[] files, Supplier supplier, HttpServletRequest req) {
        // 创建用户对象并设置用户名和密码
        System.out.println("supplier:"+supplier);

        // 设置文件上传的基础路径，并根据日期生成子路径
        String basePathStr = "C:\\Users\\Mr.Zhang\\document\\upload";
        String subPath = FileUploadUtils.makeUploadDirectoryByDate();
        basePathStr += subPath; // 文件上传的地址

        // 检查基础路径是否存在，如果不存在则创建
        File basePath = new File(basePathStr);
        if (!basePath.exists()) {
            basePath.mkdirs();
        }

        try {
            // 遍历上传的文件数组，重命名文件并保存到指定路径
            for (MultipartFile f : files) {
                String newFileName = FileUploadUtils.rename(f.getOriginalFilename());
                f.transferTo(new File(basePath, newFileName));
                supplier.setLicenseLink(subPath + newFileName);// 设置营业执照路径
            }
        } catch (Exception e) {
            throw new RuntimeException(e); // 捕获并抛出异常
        }

        Consumer consumer = consumerService.getById(supplier.getConsumerId());
        supplier.setCreateDate(new Date());
        supplier.setBalance(consumer.getBalance());
        // 保存用户信息并返回结果
        boolean b = supplierService.saveOrUpdate(supplier);
        consumer.setSupplierTag("S001-2");
        consumerService.updateById(consumer);

        return supplier;
    }



    @GetMapping("/pendingAndRejectedList")
    public Map<String, Object> getPendingAndRejectedSupplierList(
            @RequestParam(required = false) String companyName,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String checkTag
    ) {
        List<Supplier> supplierList = supplierService.getPendingAndRejectedSupplierList(companyName, page, pageSize, checkTag);
        int total = supplierService.getPendingAndRejectedSupplierCount(companyName, checkTag);
        Map<String, Object> result = new HashMap<>();
        result.put("list", supplierList);
        result.put("total", total);
        return result;
    }

    @PostMapping("/review")
    public Map<String, Object> reviewSupplier(@RequestBody Map<String, Object> data) {
        Integer supplierId = (Integer) data.get("supplierId");
        String reason = (String) data.get("reason");
        String result = (String) data.get("result");

        Supplier supplier = new Supplier();
        supplier.setSupplierId(supplierId);
        supplier.setCheckReason(reason);
        supplier.setCheckTag(result);

        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", supplierId);
        Supplier one = supplierService.getOne(queryWrapper);
        Integer consumerId = one.getConsumerId();
        Consumer consumer = consumerService.getById(consumerId);
        consumer.setSupplierTag("S001-3");
        consumerService.updateById(consumer);

        int count = supplierService.updateSupplier(supplier);

        Map<String, Object> resultMap = new HashMap<>();
        if (count > 0) {
            resultMap.put("success", true);
            resultMap.put("message", "审核成功");
        } else {
            resultMap.put("success", false);
            resultMap.put("message", "审核失败");
        }

        return resultMap;
    }
}
